// pages/patrol_record/patrol_record.js
var app = getApp();
var util = require('../../utils/util.js');
var applet_park_api_url = app.globalData.applet_park_api_url;
var applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
const {
  requestDataparams
} = require('../../utils/request.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: applet_park_api_url_imgUrl,
    leaderConfirmed: false,
    locationsid: '',
    isLeader: false,
    id: '',
    currenttype: '',
    checkname: '',
    expectedEndTime1: '',
    expectedStartTime1: '',
    checkTaskId: 1,
    currenttDate: '',
    lists: [],
    taskId: '',
    taskName: '',
    roleId: '',
    isConform: true,
    status: '',
    orderStatus: 4,
    list: [{
        // 状态
        id: 0,
        // title
        name: "一楼热水泵房",
        // 时间

      }, {
        id: 1,
        name: "工程-车库-B1F-热水泵房",

      }, {
        id: 2,
        name: "工程-学术报告厅-1F-报告厅低压配电室",

      }

      , {
        id: 3,
        name: "一楼热水泵房",

      }


    ]
  },
  checkIsconfirm() {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        taskId: options.id
      })
    }
    if (options.taskName) {
      this.setData({
        taskName: options.taskName
      })
    }
    if (options.roleId) {
      this.setData({
        roleId: options.roleId
      })
    }
    if (options.status) {
      this.setData({
        status: options.status,
        isLeader: options.isLeader
      })
    }

    // var isleader = wx.getStorageSync("isleader");
    //   this.data.isleader = isleader;
    var date = new Date()
    var year = date.getFullYear()
    var month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
    var day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    this.data.currenttDate = year + '-' + month + '-' + day;

    if (options.isLeader) {
      this.data.isLeader = options.isLeader;
    }

    this.setData(this.data)
    this.loadData();

  },
  timePro() {
    this.data.currenttDate = this.getBefOrAft(0, this.data.currenttDate);
    this.setData(this.data)
  },
  timeNaxt() {
    this.data.currenttDate = this.getBefOrAft(1, this.data.currenttDate);
    this.setData(this.data)

  },
  // 获取前天或者后一天  type: 0: 前一天 1：后一天
  getBefOrAft(type, date) {
    let forMatDate = date.replace(/-/g, '/') // 格式化日期 2019-02-23 => 2019/02/23
    let d = new Date(forMatDate) // new Date() 不能识别 2019-01-02  需转化为 2019/01/02
    if (type === 0) {
      d = +d - 1000 * 60 * 60 * 24
    } else if (type === 1) {
      d = +d + 1000 * 60 * 60 * 24 // d前面需要加上 +
    }
    d = new Date(d)
    return this.dateFormat(d) // 格式化 将日期格式转化为我们需要展示格式
  },

  // 格式化日期，传入日期对象   =>2019-01-11  
  dateFormat(date) {
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    let d = date.getDate()
    if (m <= 9) {
      m = '0' + m
    }
    if (d <= 9) {
      d = '0' + d
    }
    return y + '-' + m + '-' + d
  },
  toPartalSCan(e) {
    var deviceId = e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;
    wx.navigateTo({
      url: '../check_list/check_list?deviceId=' + deviceId + '&taskId=' + this.data.taskId + '&taskName=' + this.data.taskName + '&status=' + status + '&isLeader=true',
    })
  },
  loadData() {
    var that = this;
    var isConform = that.data.isConform;
    var orderStatus = that.data.orderStatus;
    requestDataparams('/api/checkTasks/queryTaskDevice/' + that.data.taskId, {}, 'GET').then(res => {
      if (res.data.code == 0) {
        var lists = res.data.data;
        var array = []
        for (var i = 0; i < lists.length; i++) {
          array = array.concat(lists[i]);
          console.log([i] + array[i].confirmed)

          // 确认异常单
          if (isConform == true) {
            if (array[i].confirmed == false) {
              isConform = false;
            }
          }
          if (orderStatus != 6) {
            //异常单
            if (array[i].nodeStatus == 3) {
              orderStatus = 6;
            }
          }

        }
        that.setData({
          lists: lists,
          isConform: isConform,
          orderStatus: orderStatus,
        })
        console.log(that.data.isConform)
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        });
      }
    }).catch(err => {

    });
  },
  selecttype(e) {
    this.setData({
      currenttype: e.currentTarget.dataset.index
    })

  },
  serch() {
    let lists = this.data.lists;
    // for (let i of lists){
    //   lists[i].code=
    // }
  },
  scan: function () {
    let lists = this.data.lists;
    var that = this;
    // that.submitPra();
    wx.scanCode({
      success(res) {


        if (res.result) {
          var hasNode = false;
          for (let i in lists) {
            if (lists[i].code == res.result) {
              hasNode = true;

              // if (lists[i].nodeStatus == 2) {
              //   wx.showToast({
              //     title: '当前节点已巡检过',
              //     icon: 'none',
              //     duration: 2000
              //   })
              //   return
              // }
              // lists[i].nodeStatus = 2;
              // that.data.locationsid = lists[i].id;
              lists[i].currentcode = '[当前]'
              that.data.scancode = res.result;
              that.setData(that.data);
              // that.submitPra();
            } else {
              lists[i].currentcode = ''
            }
          }

          if (!hasNode) {
            wx.showToast({
              title: '任务设备和当前设备不匹配，请选择正确设备',
              icon: 'none',
              duration: 2000
            })
          }

        }
      },
      fail() {
        wx.showToast({
          title: '扫描失败',
          icon: 'fail',
          duration: 3000
        })
      }
    })
  },
  submitPra: function () {


    var that = this;
    // var data = {
    //   'checkTaskId': that.data.checkTaskId,
    //   'deviceId': that.data.deviceId,
    //   'nodeStatus': 2
    // }
    wx.request({
      url: applet_park_api_url + '/api/checkTasks/' + that.data.checkTaskId + '/locations/' + that.data.locationsid + '?nodeStatus=2',
      method: 'PUT',
      header: {
        contentType: "application/json",
      },
      success: function (res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '巡检成功',
            icon: 'success',
            duration: 2000
          })

          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2]; //上一个页面
          prevPage.loadData();
          // wx.navigateBack();


        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '网络异常',
        });
      }

    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.loadData();
    wx.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 2000
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 获取前天或者后一天  type: 0: 前一天 1：后一天
  getBefOrAft(type, date) {
    let forMatDate = date.replace(/-/g, '/') // 格式化日期 2019-02-23 => 2019/02/23
    let d = new Date(forMatDate) // new Date() 不能识别 2019-01-02  需转化为 2019/01/02
    if (type === 0) {
      d = +d - 1000 * 60 * 60 * 24
    } else if (type === 1) {
      d = +d + 1000 * 60 * 60 * 24 // d前面需要加上 +
    }
    d = new Date(d)
    return this.dateFormat(d) // 格式化 将日期格式转化为我们需要展示格式
  },

  // 格式化日期，传入日期对象   =>2019-01-11  
  dateFormat(date) {
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    let d = date.getDate()
    if (m <= 9) {
      m = '0' + m
    }
    if (d <= 9) {
      d = '0' + d
    }
    return y + '-' + m + '-' + d
  },
  bindKeyInput: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;


    this.setData(this.data);
  },

  submit(e) {
    if (!this.data.content) {
      wx.showToast({
        title: '请先输入确认内容',
      })
    }
    requestDataparams('/api/checkTasks/updateTask', {
      taskId: this.data.taskId,
      status: this.data.orderStatus,
      remark: this.data.content
    }, 'PUT', 'json').then(res => {

      if (res.data.code == 0) {
        wx.showToast({
          title: '成功',
          icon: 'none'
        });
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面
        prevPage.loadData();
        wx.navigateBack({
          delta: 1
        })

      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        });
      }
    }).catch(err => {

    });
  },
  modifyState(item) { //员工修改巡检状态

  },
})